import { useDispatch, useSelector } from "react-redux"
import { useEffect, useState } from "react"
import { getUserProfile, logoutAsync } from "@/store/slice/userinfo.slice"
import { useHistory } from "react-router-dom"
import http from "@/utils/http"

export const useUserProfile = () => {
  const dispatch = useDispatch()
  const profile = useSelector((state) => state.userInfo.profile)
  // 获取
  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])
  // 返回
  return profile
}

// 返回一个退出登录的函数
export const useLogoutCallBack = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  return () => {
    // 删除token， 跳转到登录页面
    dispatch(logoutAsync()) // 删除token
    history.replace("/login") // 跳转到登录页
  }
}

// 封装一个获取频道数据的自定义hook

export const useChannels = () => {
  // 定义管理频道的状态
  const [channel, setChannel] = useState([])

  const getChannel = async () => {
    const { channels } = await http.get("/channels")
    setChannel(channels) // 状态更新
  }
  useEffect(() => {
    // 获取频道数据
    getChannel()
  }, [])
  return channel
}
